package mobile.game.core.support.random;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import mobile.game.core.InputStream;
import mobile.game.core.OutputStream;
import mobile.game.core.interfaces.ISerilizable;

/**
 * @author g
 *
 * 伪随机数生成器，初始时一次性生成一坨随机数，形成一个随机数循环队列，以后依次从中取随机数
 */
public class StageRandomUtils implements ISerilizable {
	/**  随机数值的上限 */
	protected static final float div = 10000f;
	
	/**  随机数循环队列 */
	protected List<Integer> seek = new ArrayList<>();
	/** 队列的大小 */
    protected int seekCount = 0;
    /** 随机数当前索引 */
    protected int seekCur = 0;
    
    public StageRandomUtils() {}
    
    public StageRandomUtils(List<Integer> seek) {
    	this.seek.addAll(seek);
    	this.seekCount = seek.size();
    	this.seekCur = 0;
    }
    
    public StageRandomUtils(int count) {
    	this.seekCur = 0;
    	this.seekCount = count;
    	
    	for (int i = 0; i < seekCount; i++) {
    		seek.add(RandomUtils.nextInt((int)div));
		}
    }
    
	@Override
	public void writeTo(OutputStream out) throws IOException {
		out.write(seek);
		out.write(seekCount);
		out.write(seekCur);
	}

	@Override
	public void readFrom(InputStream in) throws IOException {
		seek = in.read();
		seekCount = in.read();
		seekCur = in.read();
	}
	
	
    public double nextDouble() {
        return seek.get(index()) / div;
    }

    public int nextInt(int range) {
        double result = seek.get(index()) * range / div;
        return (int)(Math.floor(result));
    }

    protected int index() {
        seekCur++;
        if (seekCur >= seekCount) {
            seekCur = 0;
        }
        return seekCur;
    }

	public Collection<Integer> getSeek() {
		return Collections.unmodifiableCollection(seek);
	}

}
